package com.roy.comet;

import com.roy.comet.parse.CometSqlBean;
import com.roy.comet.parse.CometSqlParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by mc on 18/4/13.
 */
@Service
public class CometJdbcTemplate implements CometJdbcOptions {

    @Autowired
    private CometSqlParser cometSqlParser;

    @Autowired
    private CometRouter cometRouter;

    @Override
    public <K> int update(K cometKey, String sql, Object... args) {
        /**
         * 1、解析sql
         * 2、获取需要处理的表信息
         */
        CometSqlBean cometSqlBean = cometSqlParser.parseCometSql(sql);
        String tableName = cometSqlBean.getTableName();
        CometTable cometTable = cometRouter.searchCometTable(tableName.toLowerCase());

        CometStrategy cometStrategy = cometTable.getCometStrategy();

        int nodeNo = cometStrategy.getNodeNo(cometKey);
        int dbNo = cometStrategy.getDbNo(cometKey);
        int tableNo = cometStrategy.getTableNo(cometKey);

        List<CometNode> cometNodes = cometTable.getCometNodes();

        sql = cometSqlBean.getSplitSql(dbNo, tableNo);
        CometNode cometNode = cometNodes.get(nodeNo);
        JdbcTemplate jdbcTemplate = cometNode.getJdbcTemplate(nodeNo);
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public <T, K> T getObject(K cometKey,String sql, RowMapper<T> rowMapper, Object... args) {
        /**
         * 1、解析sql
         * 2、获取需要处理的表信息
         */
        CometSqlBean cometSqlBean = cometSqlParser.parseCometSql(sql);
        String tableName = cometSqlBean.getTableName();
        CometTable cometTable = cometRouter.searchCometTable(tableName.toLowerCase());

        CometStrategy cometStrategy = cometTable.getCometStrategy();

        int nodeNo = cometStrategy.getNodeNo(cometKey);
        int dbNo = cometStrategy.getDbNo(cometKey);
        int tableNo = cometStrategy.getTableNo(cometKey);

        List<CometNode> cometNodes = cometTable.getCometNodes();

        sql = cometSqlBean.getSplitSql(dbNo, tableNo);
        CometNode cometNode = cometNodes.get(nodeNo);
        JdbcTemplate jdbcTemplate = cometNode.getJdbcTemplate(nodeNo);
        return jdbcTemplate.queryForObject(sql,rowMapper,args);
    }
}
